<template>
    <!-- 导航栏 -->
    <van-nav-bar
        title="购物车"
        left-text="返回"
        left-arrow
        fixed
        placeholder
        z-index="1000"
        @click-left="OnBack"
    />

    <van-pull-refresh v-model="refreshing" @refresh="OnRefresh">
        <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="OnLoad"
        >
            <van-checkbox-group v-model="CheckedArr" ref="CheckboxGroup" @change="OnToggleGroup">
                <div class="cart" v-for="(item,index) in CartList" :key="item.id">
                    <!-- 滑动单元格 -->
                    <van-swipe-cell>
                        <van-checkbox :name="item.id"></van-checkbox>
                        <!-- 商品卡片 -->
                        <van-card
                            :thumb="item.product.thumb_text"
                            @click-thumb="ToProductInfo(item.product.id)"
                        >
                            <template #title>
                                <div class="title" @click="ToProductInfo(item.product.id)">{{ item.product.name }}</div>
                            </template>

                            <!-- 卡片的插槽部分 -->
                            <template #desc v-if="item.attrs">
                                <van-tag v-for="(attr,index) in item.attrs" :key="index" class="tag" type="primary">{{attr.value}}</van-tag>
                                <van-tag class="tag" type="warning" v-if="item.type === 'live'">直播商品</van-tag>
                            </template>

                            <!-- 卡片的插槽部分 -->
                            <template #desc v-else>
                                <van-tag class="tag" type="danger">无商品规格</van-tag>
                                <van-tag class="tag" type="warning" v-if="item.type === 'live'">直播商品</van-tag>
                            </template>

                            <template #tags>
                                <div class="price">单价：￥{{ item.price }}</div>
                            </template>

                            <template #price>
                                <div class="price">合计：￥{{ item.total }}</div>
                            </template>

                            <!-- 卡片的商品数量 步进器 -->
                            <template #num>
                                <van-stepper v-model="item.nums" disable-input :name="index" :max="item.product.live_stock ? item.product.live_stock : item.product.stock" @change="OnCartUpdate" />
                            </template>
                        </van-card>

                        <!-- 滑动单元格插槽 右侧滑动 -->
                        <template #right>
                            <van-button
                                square
                                text="删除"
                                type="danger"
                                class="delete-button"
                                @click="OnDel(item,index)"
                            />
                        </template>
                    </van-swipe-cell>
                </div>
            </van-checkbox-group>

            <van-back-top :bottom="'80'" />
        </van-list>
    </van-pull-refresh>

    <div style="height: 50px;"></div>

    <!-- 提交动作栏 -->
    <van-submit-bar :price="total" button-text="提交订单" @submit="OnSubmit">
        <van-checkbox v-model="CheckedAll" :indeterminate="IsIndeterminate" @change="OnToggle">全选</van-checkbox>
    </van-submit-bar>
</template>

<script setup>
    const { proxy } = getCurrentInstance();

    const business = proxy.$business;
    const CartList = ref([]);
    const refreshing = ref(false);
    const finished = ref(false);
    const loading = ref(false);
    const IsIndeterminate = ref(false);
    const page = ref(1);
    const CheckedArr = ref([]);
    const CheckedAll = ref(false);
    const CheckboxGroup = ref(null);
    // 接收一个 action 参数，判断是否在商品详情过来的
    const action = ref(proxy.$route.query.action ?? '');

    const OnRefresh = () =>
    {
        // 清空查询参数
        finished.value = false;
        page.value = 1;
        CartList.value = [];
        loading.value = true;

        // 加载数据方法
        setTimeout(OnLoad,1500);
    }

    const OnLoad = async () =>
    {
         // 如果等于true说明当前进行下拉刷新
         if(refreshing.value)
        {
            // 结束下拉刷新
            refreshing.value = false;
        }

        // 组装数据
        let params = {
            page:page.value,
            busid:business.value.id
        }

        // 发起请求
        let result = await proxy.$POST({
            url:'/cart/index',
            params
        })

        // 请求发送完毕后，加载状态也就完毕了
        loading.value = false;

        if(result.code === 1)
        {
            // 合并数组
            CartList.value = CartList.value.concat(result.data.list);
            let count = result.data.count;

            CartList.value.map(item => item.attrs = JSON.parse(item.attrs));

            // 如果没有更多数据了，就说明已经加载到底了
            if(CartList.value.length === count)
            {
                finished.value = true;

                return false;
            }

            page.value = page.value + 1;
        }else
        {
            finished.value = true;

            proxy.$fail(result.msg);
        }
    }

    const OnCartUpdate = async (value,{ name }) =>
    {
        let params = {
            cartid:CartList.value[name].id,
            nums:value,
            busid:business.value.id
        }

        let result = await proxy.$POST({
            url:'/cart/edit',
            params
        })
        
        if(result.code === 1)
        {
            CartList.value[name].total = (parseFloat(CartList.value[name].price) * value).toFixed(2); 
        }else{
            proxy.$fail(result.msg);
        }
    }

    const OnToggle = (value) => CheckboxGroup.value.toggleAll(value);

    // 判断单个选中
    const OnToggleGroup = () => {
        CheckedAll.value = CheckedArr.value.length == CartList.value.length
        IsIndeterminate.value = CheckedArr.value.length > 0 && CheckedArr.value.length < CartList.value.length
    }

    // 合计的价格
    const total = computed(() => {
        let total = 0;
        
        CartList.value.map((item) =>
        {
            if(CheckedArr.value.includes(item.id)) total += parseFloat(item.total);
        })

        return parseFloat(total * 100);
    })

    const OnDel = (item,index) =>
    {
        proxy.$confirm({
            title:'删除',
            message: '是否确认删除' + item.product.name + '?',
        }).then(async () =>
        {
            let params = {
                cartid:item.id,
                busid:business.value.id
            }

            // 发起请求
            let result = await proxy.$POST({
                url: '/cart/del',
                params
            })

            if(result.code === 1) 
            {
                proxy.$success({
                    message:result.msg,
                    onClose:() =>
                    {
                        CartList.value.splice(index,1);
                    }
                });
            }else 
            {
                proxy.$fail(result.msg);
            }
        }).catch(() => {})
    }

    const OnSubmit = () =>
    {
        if(CheckedArr.value.length === 0)
        {
            proxy.$fail('请选择结算商品');

            return false;
        }

        let cartids = CheckedArr.value.join(',');

        proxy.$router.push({path:'/cart/confirm',query:{cartids:cartids}});
    }

    const ToProductInfo = (proid) => proxy.$router.push({path:'/product/info',query:{proid}});

    // 返回上一页
    const OnBack = () =>
    {
        if(action.value === 'info')
        {
            proxy.$router.back();
        }else{
            proxy.$router.push('/')
        }
    }
</script>

<style scoped>
    @import url('/assets/css/cart.css');
</style>
